﻿using System;

namespace FT.Architecture.UnitOfWork
{
    public interface IUnitOfWorkInstance : IDisposable
    {
        void Commit();
        
        void Rollback();
        
        void Flush();
        
        bool IsStarted();
    }

    public sealed class StatelessUnitOfWorkInstance : UnitOfWorkInstance
    {
        public StatelessUnitOfWorkInstance(IStatelessUnitOfWork unitOfWork) : base(unitOfWork)
        {
        }
    }

    public class UnitOfWorkInstance : IUnitOfWorkInstance
    {
        private readonly IUnitOfWork _unitOfWork;
        private bool _disposed;

        public UnitOfWorkInstance(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public void Commit()
        {
            _unitOfWork.Commit();
        }

        public void Rollback()
        {
            _unitOfWork.Rollback();
        }

        public virtual void Flush()
        {
            _unitOfWork.Flush();
        }

        public virtual bool IsStarted()
        {
            return _unitOfWork.IsStarted();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (IsStarted())
                    {
                        Rollback();
                    }
                }
            }
            _disposed = true;
        }
    }
}